<template>
    
     <div class="shoping"  >
        <CartItem  ref='shopping' @click.native='showMsg' v-for="(pro,index) in products" :key='index' :id='pro.id' :name='pro.name' :img='pro.img' :price='pro.price' :num="parseInt(pro.num)" @changeFatherNum='receiveFromChirden'></CartItem>
     </div>
 
</template>

<script>
import CartItem from '../components/CartItem.vue';
export default {
  name: 'CartList',
//   data(){// 这个格式是 下面的简写
//       return {
//           products:[
//           ]
//       }
//   },
  data:function(){
      return {products:[]};
  },
  created:function(){
      let products= JSON.parse(localStorage.getItem('cart'));
      this.products=products;
      console.log('cartlist创建了!');

  },
  mounted:function(){
      console.log('cartList mount!!');
      //ref 有个对应的获取属性
      //console.log(this.$refs.shopping)
      for(let key in this.$refs.shopping){
        //   this.$refs.shopping[key].$on('fromChildren',function(num){
        //       console.log(this);//箭头函数是没有this，没有this 就往上找，上面的函数中的this 就是当前的实例，
        //                         //vue中规则，触发者的普通函数中的this就是这个触发者
        //       console.log('接收到了子组件的消息',num);
        //   });//$ob 可以开启一个监听事件
        this.$refs.shopping[key].$on('fromChildren',this.fromChildren)
      }
  },

  components:{
      CartItem:CartItem,
  },
  methods:{
      receiveFromChirden:function(num,num2,...args){
          console.log('父亲接受到了消息',num,num2,args);
      },
      showMsg(){
         // console.log('点击了');
      },
      fromChildren(num,id){
          console.log('接受子组件的实例');
          let products=JSON.parse(localStorage.getItem('cart'));
          for(let key in products){
              let currentProduct = products[key];
              if(id==currentProduct.id){
                  currentProduct.num=num;
              }
          }
          localStorage.setItem('cart',JSON.stringify(products));
      }
  }
  
}
</script>
<style scoped>
 .shoping {
     margin:0 5%;
 }
 .ym {
     width: 420px;
     height: 285px;
     background-color: #fff;
     margin-bottom: 20px;
     border-radius: 6px;
 }
 img {
     border-radius: 6px 6px 0px 0px;
     width: 420px;
 }
 .count {
     color: #E04F9F;
 }
 h4 {
     margin: 12px 40px -8px 20px;
 }
.a {
    margin-left: 20px;
    color: #7C7F92;
    font-size: 15px;
    padding-bottom: 10px;
    margin-bottom: 10px;
 }
</style>
